// AI助手应用类
class KimiAIHelper {
    constructor() {
        this.apiKey = 'sk-vjna6ovnmsubah6fzxdczzme5lkpcf5zsy6dbkjczgb5uhog';
        this.baseUrl = 'https://maas-api.lanyun.net/v1';
        this.model = '/maas/kimi/Kimi-K2-Instruct';
        this.messages = [];
        this.isTyping = false;
        this.currentStreamController = null;
        
        this.initializeElements();
        this.bindEvents();
        this.initializeMarked();
        this.updateStatus('就绪', 'ready');
    }

    // 初始化DOM元素
    initializeElements() {
        this.chatMessages = document.getElementById('chatMessages');
        this.messageInput = document.getElementById('messageInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.clearBtn = document.getElementById('clearBtn');
        this.statusDot = document.getElementById('statusDot');
        this.statusText = document.getElementById('statusText');
        this.charCount = document.getElementById('charCount');
        this.loadingOverlay = document.getElementById('loadingOverlay');
        
        // 调试信息：检查关键元素是否找到
        console.log('DOM元素初始化:', {
            chatMessages: !!this.chatMessages,
            messageInput: !!this.messageInput,
            sendBtn: !!this.sendBtn,
            clearBtn: !!this.clearBtn,
            statusDot: !!this.statusDot,
            statusText: !!this.statusText
        });
        
        // 配置相关元素
        this.configBtn = document.getElementById('configBtn');
        this.configModal = document.getElementById('configModal');
        this.closeConfigBtn = document.getElementById('closeConfigBtn');
        this.apiKeyInput = document.getElementById('apiKeyInput');
        this.baseUrlInput = document.getElementById('baseUrlInput');
        this.modelInput = document.getElementById('modelInput');
        this.toggleApiKey = document.getElementById('toggleApiKey');
        this.saveConfigBtn = document.getElementById('saveConfigBtn');
        this.testConfigBtn = document.getElementById('testConfigBtn');
    }

    // 绑定事件监听器
    bindEvents() {
        // 发送按钮点击事件
        if (this.sendBtn) {
            this.sendBtn.addEventListener('click', () => {
                console.log('发送按钮被点击');
                this.sendMessage();
            });
        } else {
            console.error('发送按钮元素未找到');
        }
        
        // 清空按钮点击事件
        if (this.clearBtn) {
            this.clearBtn.addEventListener('click', () => this.clearChat());
        } else {
            console.error('清空按钮元素未找到');
        }
        
        // 输入框事件
        if (this.messageInput) {
            this.messageInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    console.log('Enter键被按下，发送消息');
                    e.preventDefault();
                    this.sendMessage();
                }
            });
        } else {
            console.error('输入框元素未找到');
        }
        
        this.messageInput.addEventListener('input', () => {
            this.updateCharCount();
            this.autoResizeTextarea();
        });
        
        // 配置相关事件
        this.configBtn.addEventListener('click', () => this.openConfigModal());
        this.closeConfigBtn.addEventListener('click', () => this.closeConfigModal());
        this.toggleApiKey.addEventListener('click', () => this.toggleApiKeyVisibility());
        this.saveConfigBtn.addEventListener('click', () => this.saveConfig());
        this.testConfigBtn.addEventListener('click', () => this.testConnection());
        
        // 点击模态框外部关闭
        this.configModal.addEventListener('click', (e) => {
            if (e.target === this.configModal) {
                this.closeConfigModal();
            }
        });
        
        // ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.configModal.style.display === 'flex') {
                this.closeConfigModal();
            }
        });
        
        // 页面加载完成后聚焦输入框
        window.addEventListener('load', () => {
            this.messageInput.focus();
            this.loadConfig();
        });
    }

    // 初始化Marked配置
    initializeMarked() {
        if (typeof marked !== 'undefined') {
            marked.setOptions({
                highlight: function(code, lang) {
                    if (typeof hljs !== 'undefined' && lang && hljs.getLanguage(lang)) {
                        try {
                            return hljs.highlight(code, { language: lang }).value;
                        } catch (err) {}
                    }
                    return code;
                },
                breaks: true,
                gfm: true
            });
        }
    }

    // 更新状态指示器
    updateStatus(text, type = 'ready') {
        this.statusText.textContent = text;
        this.statusDot.className = 'status-dot';
        
        switch (type) {
            case 'ready':
                this.statusDot.style.background = '#10b981';
                break;
            case 'thinking':
                this.statusDot.style.background = '#f59e0b';
                break;
            case 'error':
                this.statusDot.style.background = '#ef4444';
                break;
        }
    }

    // 更新字符计数
    updateCharCount() {
        const count = this.messageInput.value.length;
        this.charCount.textContent = count;
        
        if (count > 1800) {
            this.charCount.style.color = '#ef4444';
        } else if (count > 1500) {
            this.charCount.style.color = '#f59e0b';
        } else {
            this.charCount.style.color = '#71717a';
        }
    }

    // 自动调整文本框高度
    autoResizeTextarea() {
        this.messageInput.style.height = 'auto';
        this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 128) + 'px';
    }

    // 发送消息
    async sendMessage() {
        const message = this.messageInput.value.trim();
        if (!message || this.isTyping) {
            console.log('发送消息被阻止:', { message: !!message, isTyping: this.isTyping });
            return;
        }

        console.log('发送消息:', message);
        
        // 添加用户消息
        this.addMessage(message, 'user');
        this.messages.push({ role: 'user', content: message });
        
        // 清空输入框
        this.messageInput.value = '';
        this.updateCharCount();
        this.autoResizeTextarea();
        
        // 显示打字指示器
        this.showTypingIndicator();
        
        try {
            await this.getAIResponse();
        } catch (error) {
            console.error('发送消息错误:', error);
            this.handleError(error);
        }
    }

    // 获取AI响应
    async getAIResponse() {
        this.isTyping = true;
        this.updateStatus('AI正在思考...', 'thinking');
        this.sendBtn.disabled = true;

        try {
            // 检查是否在本地环境，如果是则使用代理
            const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
            const apiUrl = isLocal ? '/api/chat' : `${this.baseUrl}/chat/completions`;
            
            console.log('API请求配置:', {
                isLocal,
                apiUrl,
                messagesCount: this.messages.length,
                lastMessage: this.messages[this.messages.length - 1]
            });
            
            const requestOptions = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    model: this.model,
                    messages: this.messages,
                    stream: true,
                    temperature: 0.7,
                    max_tokens: 2048
                })
            };
            
            // 如果不是本地环境，添加Authorization头
            if (!isLocal) {
                requestOptions.headers['Authorization'] = `Bearer ${this.apiKey}`;
            }
            
            console.log('发送API请求:', requestOptions);
            const response = await fetch(apiUrl, requestOptions);
            console.log('API响应状态:', response.status, response.statusText);

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            // 检查响应类型
            const contentType = response.headers.get('content-type');
            console.log('响应Content-Type:', contentType);
            
            if (contentType && contentType.includes('application/json')) {
                console.log('处理非流式响应');
                // 非流式响应
                await this.handleNonStreamResponse(response);
            } else {
                console.log('处理流式响应');
                // 流式响应
                await this.handleStreamResponse(response);
            }
        } catch (error) {
            throw error;
        } finally {
            this.isTyping = false;
            this.updateStatus('就绪', 'ready');
            this.sendBtn.disabled = false;
            this.hideTypingIndicator();
        }
    }

    // 处理非流式响应
    async handleNonStreamResponse(response) {
        try {
            const data = await response.json();
            const content = data.choices?.[0]?.message?.content;
            
            if (content) {
                // 创建AI消息元素
                const aiMessageElement = this.createMessageElement('', 'ai');
                this.hideTypingIndicator();
                
                // 显示完整响应
                await this.typewriterEffect(aiMessageElement, content);
                
                // 添加到消息历史
                this.messages.push({ role: 'assistant', content: content });
            } else {
                throw new Error('未收到有效的AI响应');
            }
        } catch (error) {
            console.error('处理非流式响应错误:', error);
            throw error;
        }
    }

    // 处理流式响应
    async handleStreamResponse(response) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let aiMessageElement = null;
        let fullResponse = '';
        
        // 创建AI消息元素
        aiMessageElement = this.createMessageElement('', 'ai');
        this.hideTypingIndicator();
        
        try {
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                
                const chunk = decoder.decode(value);
                console.log('收到数据块:', chunk); // 调试信息
                const lines = chunk.split('\n');
                
                for (const line of lines) {
                    if (line.trim() === '') continue;
                    
                    if (line.startsWith('data: ')) {
                        const data = line.slice(6).trim();
                        if (data === '[DONE]') continue;
                        if (data === '') continue;
                        
                        try {
                            const parsed = JSON.parse(data);
                            console.log('解析的数据:', parsed); // 调试信息
                            const delta = parsed.choices?.[0]?.delta;
                            
                            if (delta) {
                                // 处理思维链内容
                                if (delta.reasoning_content) {
                                    console.log('思维链:', delta.reasoning_content);
                                }
                                
                                // 处理主要内容
                                if (delta.content) {
                                    fullResponse += delta.content;
                                    await this.typewriterEffect(aiMessageElement, fullResponse);
                                }
                            }
                            
                            // 处理完整消息（非流式情况）
                            if (parsed.choices?.[0]?.message?.content) {
                                fullResponse = parsed.choices[0].message.content;
                                await this.typewriterEffect(aiMessageElement, fullResponse);
                            }
                        } catch (e) {
                            console.warn('解析JSON失败:', e, '原始数据:', data);
                        }
                    } else {
                        console.log('非data行:', line); // 调试信息
                    }
                }
            }
        } catch (error) {
            console.error('流式响应处理错误:', error);
            throw error;
        }
        
        // 添加完整响应到消息历史
        if (fullResponse) {
            this.messages.push({ role: 'assistant', content: fullResponse });
        } else {
            console.warn('没有收到有效的响应内容');
            throw new Error('没有收到有效的AI响应');
        }
    }

    // 打字机效果
    async typewriterEffect(element, fullText) {
        const contentDiv = element.querySelector('.message-content');
        
        // 渲染Markdown
        let renderedText = fullText;
        if (typeof marked !== 'undefined') {
            renderedText = marked.parse(fullText);
        }
        
        contentDiv.innerHTML = renderedText;
        
        // 高亮代码块
        if (typeof hljs !== 'undefined') {
            contentDiv.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightElement(block);
            });
        }
        
        // 滚动到底部
        this.scrollToBottom();
    }

    // 添加消息
    addMessage(content, type) {
        const messageElement = this.createMessageElement(content, type);
        
        // 移除欢迎消息
        const welcomeMessage = this.chatMessages.querySelector('.welcome-message');
        if (welcomeMessage) {
            welcomeMessage.remove();
        }
        
        this.scrollToBottom();
        return messageElement;
    }

    // 创建消息元素
    createMessageElement(content, type) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message message-${type}`;
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        
        if (type === 'user') {
            contentDiv.textContent = content;
        } else {
            // AI消息支持Markdown
            if (typeof marked !== 'undefined' && content) {
                contentDiv.innerHTML = marked.parse(content);
            } else {
                contentDiv.textContent = content;
            }
            
            // 高亮代码块
            if (typeof hljs !== 'undefined') {
                contentDiv.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightElement(block);
                });
            }
        }
        
        messageDiv.appendChild(contentDiv);
        this.chatMessages.appendChild(messageDiv);
        
        return messageDiv;
    }

    // 显示打字指示器
    showTypingIndicator() {
        // 移除现有的打字指示器
        this.hideTypingIndicator();
        
        const typingDiv = document.createElement('div');
        typingDiv.className = 'message message-ai';
        typingDiv.id = 'typing-indicator';
        
        const typingContent = document.createElement('div');
        typingContent.className = 'typing-indicator';
        typingContent.innerHTML = `
            <div class="typing-dots">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            </div>
            <span>AI正在思考...</span>
        `;
        
        typingDiv.appendChild(typingContent);
        this.chatMessages.appendChild(typingDiv);
        this.scrollToBottom();
    }

    // 隐藏打字指示器
    hideTypingIndicator() {
        const typingIndicator = document.getElementById('typing-indicator');
        if (typingIndicator) {
            typingIndicator.remove();
        }
    }

    // 清空聊天
    clearChat() {
        if (this.isTyping) {
            if (confirm('AI正在回复中，确定要清空对话吗？')) {
                this.stopCurrentStream();
            } else {
                return;
            }
        }
        
        this.messages = [];
        this.chatMessages.innerHTML = `
            <div class="welcome-message">
                <div class="welcome-icon">
                    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="currentColor" stroke-width="2"/>
                        <path d="M8 14S9.5 16 12 16S16 14 16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <path d="M9 9H9.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <path d="M15 9H15.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </div>
                <h2>欢迎使用 Kimi K2 AI 助手</h2>
                <p>我是基于 Kimi K2 模型的智能助手，可以帮助您解答问题、进行对话交流。请在下方输入您的问题开始对话吧！</p>
            </div>
        `;
        
        this.updateStatus('就绪', 'ready');
        this.messageInput.focus();
    }

    // 停止当前流
    stopCurrentStream() {
        if (this.currentStreamController) {
            this.currentStreamController.abort();
            this.currentStreamController = null;
        }
        this.isTyping = false;
        this.hideTypingIndicator();
        this.updateStatus('就绪', 'ready');
        this.sendBtn.disabled = false;
    }

    // 处理错误
    handleError(error) {
        console.error('AI响应错误:', error);
        
        this.hideTypingIndicator();
        
        let errorMessage = '抱歉，发生了一个错误。请稍后重试。';
        
        if (error.message.includes('401')) {
            errorMessage = '认证失败，请检查API密钥是否正确。';
        } else if (error.message.includes('429')) {
            errorMessage = '请求过于频繁，请稍后重试。';
        } else if (error.message.includes('500')) {
            errorMessage = '服务器内部错误，请稍后重试。';
        } else if (error.message.includes('network') || error.message.includes('fetch')) {
            errorMessage = '网络连接错误，请检查网络连接。';
        }
        
        this.addMessage(`❌ ${errorMessage}`, 'ai');
        this.updateStatus('错误', 'error');
        
        // 3秒后恢复就绪状态
        setTimeout(() => {
            this.updateStatus('就绪', 'ready');
        }, 3000);
    }

    // 滚动到底部
    scrollToBottom() {
        setTimeout(() => {
            this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
        }, 100);
    }

    // 显示加载动画
    showLoading() {
        this.loadingOverlay.classList.add('show');
    }

    // 隐藏加载动画
    hideLoading() {
        this.loadingOverlay.classList.remove('show');
    }

    // 复制到剪贴板
    copyToClipboard(text) {
        if (navigator.clipboard && window.isSecureContext) {
            return navigator.clipboard.writeText(text);
        } else {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            return new Promise((resolve, reject) => {
                document.execCommand('copy') ? resolve() : reject();
                textArea.remove();
            });
        }
    }

    // 配置管理方法
    openConfigModal() {
        this.configModal.style.display = 'flex';
        this.loadConfigToForm();
    }

    closeConfigModal() {
        this.configModal.style.display = 'none';
    }

    toggleApiKeyVisibility() {
        const type = this.apiKeyInput.type === 'password' ? 'text' : 'password';
        this.apiKeyInput.type = type;
        this.toggleApiKey.textContent = type === 'password' ? '👁️' : '🙈';
    }

    loadConfig() {
        const savedConfig = localStorage.getItem('kimiAIConfig');
        if (savedConfig) {
            try {
                const config = JSON.parse(savedConfig);
                this.apiKey = config.apiKey || this.apiKey;
                this.baseUrl = config.baseUrl || this.baseUrl;
                this.model = config.model || this.model;
            } catch (error) {
                console.warn('Failed to load config:', error);
            }
        }
    }

    loadConfigToForm() {
        this.apiKeyInput.value = this.apiKey;
        this.baseUrlInput.value = this.baseUrl;
        this.modelInput.value = this.model;
    }

    saveConfig() {
        const config = {
            apiKey: this.apiKeyInput.value.trim(),
            baseUrl: this.baseUrlInput.value.trim() || 'https://maas-api.lanyun.net/v1',
            model: this.modelInput.value.trim() || '/maas/kimi/Kimi-K2-Instruct'
        };

        // 验证配置
        if (!config.apiKey) {
            alert('请输入API密钥');
            return;
        }

        // 保存到实例和本地存储
        this.apiKey = config.apiKey;
        this.baseUrl = config.baseUrl;
        this.model = config.model;
        
        localStorage.setItem('kimiAIConfig', JSON.stringify(config));
        
        this.closeConfigModal();
        this.updateStatus('配置已保存', 'ready');
        
        setTimeout(() => {
            this.updateStatus('就绪', 'ready');
        }, 2000);
    }

    async testConnection() {
        const apiKey = this.apiKeyInput.value.trim();
        const baseUrl = this.baseUrlInput.value.trim() || 'https://maas-api.lanyun.net/v1';
        const model = this.modelInput.value.trim() || '/maas/kimi/Kimi-K2-Instruct';

        if (!apiKey) {
            alert('请先输入API密钥');
            return;
        }

        this.testConfigBtn.disabled = true;
        this.testConfigBtn.textContent = '测试中...';

        try {
            const response = await fetch(`${baseUrl}/chat/completions`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify({
                    model: model,
                    messages: [{ role: 'user', content: 'Hello' }],
                    max_tokens: 10
                })
            });

            if (response.ok) {
                alert('✅ 连接测试成功！');
            } else {
                const errorData = await response.text();
                alert(`❌ 连接测试失败: ${response.status} ${response.statusText}\n${errorData}`);
            }
        } catch (error) {
            alert(`❌ 连接测试失败: ${error.message}`);
        } finally {
            this.testConfigBtn.disabled = false;
            this.testConfigBtn.textContent = '测试连接';
        }
    }
}

// 工具函数
class Utils {
    // 防抖函数
    static debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 节流函数
    static throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }

    // 格式化时间
    static formatTime(date) {
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 复制文本到剪贴板
    static async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            return true;
        } catch (err) {
            console.error('复制失败:', err);
            return false;
        }
    }
}



// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOMContentLoaded事件触发，开始初始化应用');
    
    // 检查必要的依赖
    if (typeof marked === 'undefined') {
        console.warn('Marked.js 未加载，Markdown渲染功能将不可用');
    }
    
    if (typeof hljs === 'undefined') {
        console.warn('Highlight.js 未加载，代码高亮功能将不可用');
    }
    
    // 初始化应用
    try {
        window.aiHelper = new KimiAIHelper();
        console.log('AI助手应用初始化成功');
    } catch (error) {
        console.error('AI助手应用初始化失败:', error);
    }
    
    // 添加全局错误处理
    window.addEventListener('error', (event) => {
        console.error('全局错误:', event.error);
    });
    
    window.addEventListener('unhandledrejection', (event) => {
        console.error('未处理的Promise拒绝:', event.reason);
    });
});

// 导出类供其他脚本使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { KimiAIHelper, Utils };
}